// 运行时配置
import { apiClients, tokenManager } from '@/services/apiClient';
import { getUserPermissions } from '@/utils/permissions';
import type { UserProfile } from '@/services/generated/src/index';

// 定义初始状态类型
export interface InitialStateType {
  name: string;
  currentUser?: UserProfile; // 当前登录用户信息
  userPermissions?: string[]; // 用户权限列表 (Django格式: app_label.action_model)
  userGroups?: string[]; // 用户组列表 (替代角色)
}

// 获取当前用户信息
const fetchUserInfo = async (): Promise<UserProfile | undefined> => {
  try {
    const token = tokenManager.getToken();
    if (!token) {
      return undefined;
    }

    const response = await apiClients.auth.authMeRetrieve();
    const userData = (response as any).data || response;
    return userData;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    // 如果获取用户信息失败，清除token
    tokenManager.removeToken();
    return undefined;
  }
};

// 获取用户权限和组信息
const fetchUserPermissionsAndGroups = async (): Promise<{permissions: string[], groups: string[]}> => {
  try {
    const response = await apiClients.permissions.permissionsUserGroupAssignmentsUserPermissionsRetrieve();
    const permissionData = (response as any).data || response;

    return {
      permissions: permissionData.permissions || [],
      groups: permissionData.groups || []
    };
  } catch (error) {
    console.error('获取用户权限和组信息失败:', error);
    return { permissions: [], groups: [] };
  }
};

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<InitialStateType> {
  // 获取当前用户信息
  const currentUser = await fetchUserInfo();

  let userPermissions: string[] = [];
  let userGroups: string[] = [];

  // 如果用户已登录，获取权限信息
  if (currentUser) {
    const permissionData = await fetchUserPermissionsAndGroups();
    userPermissions = permissionData.permissions;
    userGroups = permissionData.groups;
  }

  return {
    name: '用户管理系统',
    currentUser,
    userPermissions,
    userGroups,
  };
}

export const layout = () => {
  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
    },
  };
};
